<!--
 * @Description: 
 * @Author: mmzhang
 * @Date: 2022-03-04 09:54:45
 * @LastEditTime: 2023-02-16 09:48:32
-->
<template>
  <div class="Udeal-task" style="height: 100%">
    <dt-loading :loading="loading || loadingTips" />
    <!--案场待办-->
    <div v-if="buildTab != '' && isbuildFlag == 'buildpage'">
      <div class="flex flex-horizontal-between" v-if="buildTab == 'myUDealTask' && taskInfo.taskNumbers">
        <p
          class="tip-text outer-width"
          :style="{ height: showFlag ? 'auto' : '40px', 'overflow-y': 'hidden' }">
          <Icon type="md-alert" :size="18" color="#FAAD14" style="line-height: 26px; margin-right: 10px" />
          <span class="inner-width">
            您所在的其他{{ taskInfo.buildingNumbers }}个案场还有{{
              taskInfo.taskNumbers
            }}个任务需完成，切换案场：
          </span>
          <span
            class="view hand inner-width"
            v-for="(item, index) in taskInfo.buildingInfo"
            :key="index"
            @click="viewBuildTask(item)">
            {{ item.housesName }}
          </span>
        </p>
        <Button
          @click="downUpFun"
          type="primary"
          v-if="showBtn"
          :icon="showFlag ? 'ios-arrow-up' : 'ios-arrow-down'">
          {{ showFlag ? '收起' : '展开' }}
        </Button>
      </div>
      <p class="tip-text" v-if="buildTab == 'buildUDealTask' && taskInfo.buildingTaskNumbers">
        <Icon type="md-alert" :size="18" color="#FAAD14" style="line-height: 26px; margin-right: 10px" />
        {{
          taskInfo.transmitTaskCount > 0
            ? '以下为其他人员待办，标红的数据为转交给您的流程，您可代为完成！'
            : '以下为其他人员待办，您可代为完成！'
        }}
      </p>
    </div>
    <div v-if="isbuildFlag == 'nobuildpage' && buildTab == 'buildUDealTask'">
      <p class="tip-text" v-if="taskInfo.adminNumbers && taskInfo.transmitTaskCount > 0">
        <Icon type="md-alert" :size="18" color="#FAAD14" style="line-height: 26px; margin-right: 10px" />
        以下为其他人员待办，标红的数据为转交给您的流程，您可代为完成！
      </p>
    </div>
    <div class="empty-page" v-if="emptyFlag">
      <img src="@/assets/images/empty-page.png" alt="" />
      <p>当前登录角色无待办任务</p>
    </div>
    <div
      v-else
      class="flex flex-horizontal-between"
      :style="{ height: routeName == 'UdealTask' ? 'calc(100% - 30px)' : 'calc(100% - 80px)' }">
      <div class="task-content">
        <ul class="task-left">
          <li
            v-for="(item, index) in taskList"
            :key="index"
            :class="{ selected: task && task.taskName == item.taskName }"
            @click="changeTask(item)">
            <p>{{ item.taskCount }}</p>
            <p>{{ item.taskName }}</p>
          </li>
        </ul>
      </div>
      <div class="right-content">
        <Tabs v-model="taskStatus" :animated="false" @on-click="searchListFun()">
          <TabPane
            :label="item.taskStatusName + '（' + item.taskStatusCount + '）'"
            :name="item.taskStatus.toString()"
            v-for="(item, index) in statusList"
            :key="index"></TabPane>
        </Tabs>
        <div class="flex flex-vertical-center" style="margin-bottom: 10px" v-if="tipsObj.tipsContent != ''">
          <p>{{ tipsObj.tipsContent }}</p>
          <Button
            style="margin-left: 20px"
            @click="viewOwnerTask"
            type="primary"
            v-if="tipsObj.tipsMenuStatus">
            查看我要处理的任务
          </Button>
        </div>
        <!--表格-->
        <dt-grid
          ref="table"
          :page="page"
          :onFetch="onFetch"
          :row-style="rowStyle"
          v-if="
            task &&
            ((task.taskType.toString() != '12,13' && task.taskType.toString() != '23') ||
              taskStatus == 2 ||
              taskStatus == 5 ||
              taskStatus == 3)
          " />
        <dt-grid
          ref="table"
          :page="page"
          :onFetch="onFetch"
          :mergeCells="mergeCells"
          :tree="{ showIcon: false }"
          :row-style="rowStyle"
          v-else />
      </div>
    </div>
  </div>
</template>
<script>
  import buildMgr from '@/biz/building'
  import store from '@/store'
  import { buildPage } from '@/router/buildPage.js'
  import taskColumn from './components/column'
  import taskMgr from '@/biz/UdealTask/task'
  import caseMgr from '@/biz/crimeSceneList'
  import clueCustomerMgr from '@/biz/customer/clueCustomer.js'
  import tool from '@/common/tool.js'
  import { linkPage } from '@/biz/UdealTask/link'
  import dt from '@dt/dt'

  export default {
    mixins: [linkPage],
    data() {
      return {
        routeName: '',
        isbuildFlag: 'buildpage',
        page: {
          current: 1,
          rows: 50
        },
        mergeCells: [],
        taskList: [],
        task: null,
        taskStatus: '', // 待办1  今日已完成101 逾期未处理3 已完成2 逾期已完成5
        statusList: [],
        loading: true,
        emptyFlag: false,
        loadingTips: false,
        tipsObj: {
          tipsContent: '',
          tipsMenuStatus: false
        },
        buildTab: '',
        taskInfo: {},
        showFlag: false,
        showBtn: true
      }
    },
    watch: {
      $route(to, from) {
        this.routeName = to.name
        // 路由改变要刷新数据，页面不刷
        if (to.name == 'UdealTask') {
          if (this.unlockingMenu('0113000000')) {
            this.emptyFlag = false
            this.loading = true
            this.getLeftTaskCount()
          } else {
            this.emptyFlag = true
            this.loading = false
          }
        }
      }
    },
    mounted() {
      this.routeName = this.$route.name
      if (
        this.unlockingMenu('0113000000') &&
        this.$route.name != 'taskListPage' &&
        this.$route.name != 'taskListPageWork'
      ) {
        this.emptyFlag = false
        this.loading = true
        clueCustomerMgr.getChannel(false)
        this.getLeftTaskCount()
      } else {
        this.emptyFlag = true
        this.loading = false
      }
      window.addEventListener(
        'resize',
        () => {
          this.showUpDownBtn()
        },
        false
      )
    },
    methods: {
      rowStyle(e) {
        return {
          'background-color': e.row.transmitUserId == dt.userInfo().userId ? '#FFE4E1' : '#fff'
        }
      },
      downUpFun() {
        this.showFlag = !this.showFlag
        this.$refs.table.fixHeight()
      },
      // 自适应是否展示展开收起按钮
      showUpDownBtn() {
        if (this.buildTab == 'myUDealTask' && this.taskInfo.taskNumbers) {
          this.$nextTick(function () {
            let list = document.querySelectorAll('.inner-width')
            let outerWidth = document.querySelector('.outer-width')
              ? document.querySelector('.outer-width').offsetWidth
              : 0
            let sumWidth = 28
            for (let i = 0; i < list.length; i++) {
              sumWidth += list[i].offsetWidth
            }
            this.showBtn = sumWidth > outerWidth ? true : false
          })
        }
      },
      // 查看案场待办
      viewBuildTask(buildItem) {
        let params = {
          housesId: buildItem.housesId
        }

        store.dispatch('setRouterList', [])
        caseMgr.buildinghousesList(params).then((res) => {
          let item = { ...res.list[0] }
          // 更新案场
          buildMgr.updateBuildInfo(item)
          this.$tool.setStorage({ caseBuildingId: JSON.stringify(item.housesId) })
          store.dispatch('setRouterList', buildPage)
          this.getLeftTaskCount()
          this.$emit('onTaskInfo')
        })
      },
      // 是否是案场内待办 工作台待办
      resetTaskFun() {
        this.task = null
      },
      buildInitFun(buildTab) {
        this.buildTab = buildTab
        this.emptyFlag = false
        this.loading = true
        clueCustomerMgr.getChannel(false)
        this.getLeftTaskCount()
      },
      buildTaskInfo(taskInfo) {
        this.taskInfo = taskInfo
        this.showUpDownBtn()
      },
      // 查看我要处理的任务
      viewOwnerTask() {
        this.$refs.table.init(this, new taskColumn(this), {
          ownerText: '我要处理的任务'
        })
        this.$refs.table.fetch(true)
      },
      // 获取左侧
      getLeftTaskCount() {
        this.isbuildFlag = this.$tool.getStorage('isbuildFlag')
        //判断是不是案场首页点击跳转
        let req = ''
        let params = {}
        if (this.$route.name == 'taskListPage') {
          params = {
            buildingId: this.$dt.buildInfo().housesId,
            type: this.buildTab == 'myUDealTask' ? 1 : 2
          }
          req = taskMgr.getLeftTaskCountWithBuildingId(params)
        } else if (this.$route.name == 'taskListPageWork') {
          params = {
            type: this.buildTab == 'myUDealTask' ? 1 : 2
          }
          req = taskMgr.getLeftTaskCountWithOrg(params)
        } else {
          params = {}
          req = taskMgr.getLeftTaskCount(params)
        }

        req.then((res) => {
          if (res.length) {
            this.taskList = res
            let curTask = {}
            if (this.task) {
              curTask = res.filter((item) => item.taskName == this.task.taskName)[0]
            }
            // 选中第一个不为零的待办任务  如果都为零 选中第一个 区分之前选择的定位
            if (!curTask || !this.task) {
              this.task = res[0]
              for (let i = 0; i < res.length; i++) {
                if (res[i].taskCount != 0) {
                  this.task = res[i]
                  break
                }
              }
            }
            this.getTopTaskStatusCount()
          } else {
            this.emptyFlag = true
            this.loading = false
          }
        })
      },
      // 获取头部
      getTopTaskStatusCount() {
        this.statusList = []
        let params = {}
        let req = ''
        if (this.$route.name == 'taskListPage') {
          params = {
            buildingId: this.$dt.buildInfo().housesId,
            type: this.buildTab == 'myUDealTask' ? 1 : 2,
            taskName: this.task.taskName
          }
          req = taskMgr.getTopTaskStatusCountWithBuildingId(params)
        } else if (this.$route.name == 'taskListPageWork') {
          // 工作台
          params = {
            type: this.buildTab == 'myUDealTask' ? 1 : 2,
            taskName: this.task.taskName
          }
          req = taskMgr.getTopTaskStatusCountWithOrg(params)
        } else {
          params = {
            taskName: this.task.taskName
          }
          req = taskMgr.getTopTaskStatusCount(params)
        }

        req.then((res) => {
          this.statusList = res
          if (this.taskStatus == '') {
            this.taskStatus = this.statusList[0].taskStatus.toString()
          }
          this.searchListFun()
        })
      },
      // 任务责任人提示
      getTaskMsgTips() {
        let params = {
          taskStatus: this.taskStatus == 1 ? 1 : 3,
          taskType: this.task.taskType
        }
        this.loadingTips = true
        taskMgr.getTaskMsgTips(params).then((res) => {
          this.tipsObj = { ...res }
          this.loadingTips = false
        })
      },
      // 改变
      changeTask(item) {
        this.loading = true
        this.task = item
        this.taskStatus = ''
        this.$refs.table.emptyGrid()
        this.getTopTaskStatusCount()
      },
      searchListFun() {
        if (
          this.taskStatus == 1 &&
          this.$route.name != 'taskListPage' &&
          this.$route.name != 'taskListPageWork'
        ) {
          this.getTaskMsgTips()
        } else {
          this.tipsObj = {
            tipsContent: '',
            tipsMenuStatus: false
          }
        }

        this.page = {
          current: 1,
          rows: 50
        }

        this.$nextTick(function () {
          this.$refs.table.init(this, new taskColumn(this))
          this.$refs.table.throwFilter() && this.$refs.table.throwFilter().clear()
          this.$refs.table.fetch(true)
        })
      },
      onFetch(data) {
        let params = {}
        let req = ''

        if (this.$route.name == 'taskListPage') {
          params = {
            buildingId: this.$dt.buildInfo().housesId,
            type: this.buildTab == 'myUDealTask' ? 1 : 2,
            taskIds: this.statusList.filter((item) => item.taskStatus == this.taskStatus)[0].taskIds,
            ...data,
            taskType: this.task.taskType,
            queryType: data.ownerText ? 1 : null
          }
          req = taskMgr.getTaskList(params)
        } else if (this.$route.name == 'taskListPageWork') {
          // 工作台
          params = {
            type: this.buildTab == 'myUDealTask' ? 1 : 2,
            taskIds: this.statusList.filter((item) => item.taskStatus == this.taskStatus)[0].taskIds,
            ...data,
            taskType: this.task.taskType,
            queryType: data.ownerText ? 1 : null
          }
          req = taskMgr.getTaskListWithOrg(params)
        } else {
          params = {
            taskIds: this.statusList.filter((item) => item.taskStatus == this.taskStatus)[0].taskIds,
            ...data,
            taskType: this.task.taskType,
            queryType: data.ownerText ? 1 : null
          }
          req = taskMgr.getTaskList(params)
        }

        return req.then((res) => {
          console.log(res)
          this.$refs.table.fixHeight()
          this.$refs.table.init(this, new taskColumn(this))
          this.loading = false

          if (
            (this.task.taskType.toString() != '12,13' && this.task.taskType != '23') ||
            this.taskStatus == 2 ||
            this.taskStatus == 5 ||
            this.taskStatus == 3
          ) {
            return {
              total: res.total,
              list: res.records
            }
          } else {
            let arrRecords = this.mergeFun(this.resolveArrFun(res.records, ['annotationTaskRemark']))

            arrRecords.forEach((item, index) => {
              item.divisionName = item.children[0].annotationTaskRemark
              item.buildingName = ''
              this.$refs.table.treeExpand(item)
            })
            return {
              total: res.total,
              list: arrRecords
            }
          }
        })
      },
      // 合并单元格
      mergeFun(arrRecords) {
        this.mergeCells = []
        let mergeObj = {}
        let spanArr = []
        arrRecords.forEach((item) => {
          spanArr.push(item)
          if (item.children) {
            spanArr = spanArr.concat(item.children)
          }
        })
        spanArr.forEach((item, index) => {
          if (item.children) {
            mergeObj = {
              row: index,
              col: 0,
              rowspan: 0,
              colspan: 11
            }
          }
          this.mergeCells.push(mergeObj)
        })

        return arrRecords
      },
      resolveArrFun(data, keys = []) {
        //keys可以传一个数组
        var c = []
        var d = {}
        for (var element of data) {
          let element_keyStr = ''
          let element_key = []
          let element_keyObj = {}
          for (var key of keys) {
            element_key.push(element[key])
            element_keyObj[key] = element[key]
          }
          element_keyStr = element_key.join('_')
          if (!d[element_keyStr]) {
            c.push({
              ...element_keyObj,
              children: [element]
            })
            d[element_keyStr] = element
          } else {
            for (var ele of c) {
              let isTrue = keys.some((key) => {
                return ele[key] != element[key]
              })
              if (!isTrue) {
                ele.children.push(element)
              }
            }
          }
        }
        return c
      },
      onClick(row) {
        let params = {
          housesId: row.buildingId
        }
        // 判断案场外跳转
        console.log('zmm ~ file: link.js:9 ~ linkPageFun ~ this.$route.name:', this.$route.name)

        if (this.$route.name == 'UdealTask') {
          caseMgr.buildinghousesList(params).then((res) => {
            let item = { ...res.list[0] }
            // 更新案场
            buildMgr.updateBuildInfo(item)
            this.$tool.setStorage({ caseBuildingId: JSON.stringify(item.housesId) })
            store.dispatch('setRouterList', buildPage)

            this.linkPageFun(row)
          })
        } else {
          this.linkPageFun(row)
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .Udeal-task {
    .empty-page {
      margin: 5% 20%;
      display: flex;
      justify-content: center;
      flex-flow: wrap;

      p {
        width: 100%;
        text-align: center;
        line-height: 30px;
      }
    }

    .task-content {
      height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
      border: 1px solid #dadada;
      .task-left {
        width: 150px;
        background-color: #dadada;
        text-align: center;
        li {
          padding: 8px 0;
          cursor: pointer;
        }
      }
    }
    .right-content {
      width: calc(100% - 180px);
    }

    .selected {
      background-color: #fff;
    }

    ::v-deep .ivu-tabs-nav .ivu-tabs-tab {
      padding: 15px 16px;
    }

    ::v-deep .elx-table .elx-cell--tree-node.is--active {
      font-weight: bold;
    }

    .tip-text {
      margin-right: 10px;
      width: 100%;
      line-height: 40px;
      background-color: rgba(254, 252, 236, 1);
    }

    .view {
      padding-left: 10px;
      color: #2d8cf0;
    }
  }
</style>
